/**
 * 文档转换工具类
 * 提供Markdown转换为PDF和DOCX的MCP接口
 */

import { promises as fs } from 'fs';
import { dirname } from 'path';
import type { ToolResult } from '../../core/tool-schema.js';
import { createChildLogger, createErrorLogContext } from '../../utils/logger.js';
import { createConverter } from './index.js';
import type { ConversionOptions, DocxOptions, PdfOptions } from './types.js';

export interface MarkdownToPdfParams {
  /** Markdown内容 */
  markdown: string;
  /** 输出PDF文件路径 */
  outputPath: string;
  /** PDF选项 */
  options?: PdfOptions & ConversionOptions;
}

export interface MarkdownToDocxParams {
  /** Markdown内容 */
  markdown: string;
  /** 输出DOCX文件路径 */
  outputPath: string;
  /** DOCX选项 */
  options?: DocxOptions & ConversionOptions;
}

export interface MarkdownFileToPdfParams {
  /** Markdown文件路径 */
  filePath: string;
  /** 输出PDF文件路径 */
  outputPath: string;
  /** PDF选项 */
  options?: PdfOptions & ConversionOptions;
}

export interface MarkdownFileToDocxParams {
  /** Markdown文件路径 */
  filePath: string;
  /** 输出DOCX文件路径 */
  outputPath: string;
  /** DOCX选项 */
  options?: DocxOptions & ConversionOptions;
}

export class ConvertTool {
  private logger = createChildLogger('ConvertTool');

  /**
   * 确保输出目录存在
   */
  private async ensureOutputDirectory(outputPath: string): Promise<void> {
    const dir = dirname(outputPath);
    try {
      await fs.mkdir(dir, { recursive: true });
    } catch (error) {
      this.logger.error(
        'Failed to create output directory',
        createErrorLogContext(error, {
          directory: dir,
          outputPath,
        })
      );
      throw error;
    }
  }

  /**
   * 转换Markdown内容为PDF
   */
  async markdownToPdf(params: MarkdownToPdfParams): Promise<ToolResult> {
    try {
      this.logger.info('Starting markdown to PDF conversion', {
        outputPath: params.outputPath,
        contentLength: params.markdown.length,
      });

      await this.ensureOutputDirectory(params.outputPath);

      const converter = createConverter();
      const result = await converter.toPdf(
        params.markdown,
        params.outputPath,
        params.options || {}
      );

      this.logger.info('Markdown to PDF conversion completed successfully', {
        outputPath: result.outputPath,
        size: result.size,
      });

      return {
        success: true,
        data: result,
        message: result.message,
      };
    } catch (error) {
      this.logger.error(
        'Markdown to PDF conversion failed',
        createErrorLogContext(error, {
          outputPath: params.outputPath,
        })
      );
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error),
      };
    }
  }

  /**
   * 转换Markdown内容为DOCX
   */
  async markdownToDocx(params: MarkdownToDocxParams): Promise<ToolResult> {
    try {
      this.logger.info('Starting markdown to DOCX conversion', {
        outputPath: params.outputPath,
        contentLength: params.markdown.length,
      });

      await this.ensureOutputDirectory(params.outputPath);

      const converter = createConverter();
      const result = await converter.toDocx(
        params.markdown,
        params.outputPath,
        params.options || {}
      );

      this.logger.info('Markdown to DOCX conversion completed successfully', {
        outputPath: result.outputPath,
        size: result.size,
      });

      return {
        success: true,
        data: result,
        message: result.message,
      };
    } catch (error) {
      this.logger.error(
        'Markdown to DOCX conversion failed',
        createErrorLogContext(error, {
          outputPath: params.outputPath,
        })
      );
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error),
      };
    }
  }

  /**
   * 转换Markdown文件为PDF
   */
  async markdownFileToPdf(params: MarkdownFileToPdfParams): Promise<ToolResult> {
    try {
      this.logger.info('Starting markdown file to PDF conversion', {
        filePath: params.filePath,
        outputPath: params.outputPath,
      });

      await this.ensureOutputDirectory(params.outputPath);

      const converter = createConverter();
      const result = await converter.fileToPdf(
        params.filePath,
        params.outputPath,
        params.options || {}
      );

      this.logger.info('Markdown file to PDF conversion completed successfully', {
        outputPath: result.outputPath,
        size: result.size,
      });

      return {
        success: true,
        data: result,
        message: result.message,
      };
    } catch (error) {
      this.logger.error(
        'Markdown file to PDF conversion failed',
        createErrorLogContext(error, {
          filePath: params.filePath,
          outputPath: params.outputPath,
        })
      );
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error),
      };
    }
  }

  /**
   * 转换Markdown文件为DOCX
   */
  async markdownFileToDocx(params: MarkdownFileToDocxParams): Promise<ToolResult> {
    try {
      this.logger.info('Starting markdown file to DOCX conversion', {
        filePath: params.filePath,
        outputPath: params.outputPath,
      });

      await this.ensureOutputDirectory(params.outputPath);

      const converter = createConverter();
      const result = await converter.fileToDocx(
        params.filePath,
        params.outputPath,
        params.options || {}
      );

      this.logger.info('Markdown file to DOCX conversion completed successfully', {
        outputPath: result.outputPath,
        size: result.size,
      });

      return {
        success: true,
        data: result,
        message: result.message,
      };
    } catch (error) {
      this.logger.error(
        'Markdown file to DOCX conversion failed',
        createErrorLogContext(error, {
          filePath: params.filePath,
          outputPath: params.outputPath,
        })
      );
      return {
        success: false,
        error: error instanceof Error ? error.message : String(error),
      };
    }
  }
}
